package com.cloudcc.mobile.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.ChosePersonAdapter;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.entity.User;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.UserParser;
import com.cloudcc.mobile.service.UserService;
import com.cloudcc.mobile.util.AsyncTaskBase;
import com.cloudcc.mobile.util.CharacterParser;
import com.cloudcc.mobile.util.PinyinComparator;
import com.cloudcc.mobile.util.PinyinUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.cloudcc.mobile.weight.CustomListView;
import com.cloudcc.mobile.weight.LoadingView;
import com.cloudcc.mobile.weight.SideBar;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ChosePerson extends BaseActivity {
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private CustomListView sortListView;
    private SideBar sideBar;
    private TextView dialog, title, finish;
    private ClearEditText mClearEditText;
    private Map<String, User> callRecords;
    private LoadingView mLoadingView;
    private ChosePersonAdapter adapter;
    private ImageView set;
    private StringBuilder sb = new StringBuilder();

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<CoworkerEntity> SourceDateList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private LinearLayout contaxt_bg;
    private float ux, dx;
    private TextView no_contaxt;
    private ImageView no_network;
    private FrameLayout frame;

    @Override
    public int getLayoutId() {
        return R.layout.chat_contaxt3;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        setupView();
        initData();
        addListener();
    }

    /**
     * 滑动返回
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 当按下时处理
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            dx = ev.getX();
        } else if (ev.getAction() == MotionEvent.ACTION_UP) {// 松开处理
            ux = ev.getX();
            if ((int) (ux - dx) > DensityUtils.getScreenWidth(mContext) / 2
                    && ux > dx) {
                finish();
                // 设置切换动画，从右边进入，左边退出
                overridePendingTransition(R.anim.in_from_left,
                        R.anim.out_to_right);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        try {
            AppContext.getInstance().contactmap.clear();
            super.onDestroy();
        } catch (Exception e) {
            Tools.handle(e);
        }
    }

    private void addListener() {
        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", sb.toString());
                setResult(RESULT_OK, intent);
                ChosePerson.this.finish();
            }
        });
        /**
         * 点击刷新
         */
        frame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoadingView.setVisibility(View.VISIBLE);
                frame.setVisibility(View.GONE);
                new AsyncTaskConstact(mLoadingView).execute(0);

            }
        });
        // listview 做监听
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                String name = adapter.getItem(arg2-1).getName();
                String userId = adapter.getItem(arg2-1).getId();
                Intent intent = new Intent();
                intent.putExtra("name", name);
                intent.putExtra("userId", userId);
                setResult(RESULT_OK, intent);
                ChosePerson.this.finish();
            }
        });
        set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChosePerson.this.finish();
            }
        });

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @SuppressLint("NewApi")
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });
        /**
         * 下拉刷新
         */
        sortListView.setOnRefreshListener(new CustomListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new AsyncTaskConstact(mLoadingView).execute(0);
            }
        });
    }

    private void setupView() {
        frame = (FrameLayout) findViewById(R.id.frame);
        title = (TextView) findViewById(R.id.title);
        if ("en".equals(mEns)) {
            title.setText("Choose the approver");
        }else{
            title.setText("选择审批人");
        }

        finish = (TextView) findViewById(R.id.finish);
        finish.setVisibility(View.GONE);
        set = (ImageView) findViewById(R.id.chatcontact_menubtn);
        set.setImageResource(R.drawable.fujin_back);
        no_contaxt = (TextView) findViewById(R.id.empty_contaxt);
        no_network = (ImageView) findViewById(R.id.contaxt_no_work);
        contaxt_bg = (LinearLayout) findViewById(R.id.contaxt_bg);
        mLoadingView = (LoadingView) findViewById(R.id.contactloading);
        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sortListView = (CustomListView) findViewById(R.id.chat_contaxt_list);
        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
        mClearEditText.setHint("搜索审批人");
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        SourceDateList = new ArrayList<CoworkerEntity>();
        DbUtils db = DbUtils.create(this,
                UserManager.getManager().getUser().userId + "chat");
        try {
            if (db.tableIsExist(CoworkerEntity.class)) {
                SourceDateList = db.findAll(CoworkerEntity.class);
                // 根据a-z进行排序源数据
                Collections.sort(SourceDateList, pinyinComparator);
                adapter = new ChosePersonAdapter(this, SourceDateList);
                sortListView.setAdapter(adapter);
                // 获取审批人id
                // Log.d("SourceDateList", SourceDateList.get(0).getId()+"这个是");
                contaxt_bg.setVisibility(View.VISIBLE);
            } else {
                adapter = new ChosePersonAdapter(this, SourceDateList);
                // Log.d("SourceDateList", SourceDateList.get(0).getId()+"这个是");
                sortListView.setAdapter(adapter);
            }
        } catch (DbException e) {
            Tools.handle(e);
        }
    }

    private void noData() {
        if (SourceDateList.size() == 0) {
            frame.setVisibility(View.VISIBLE);
            no_contaxt.setVisibility(View.VISIBLE);
            no_network.setVisibility(View.GONE);
            contaxt_bg.setVisibility(View.GONE);
        }
    }

    private void noNetWork() {
        if (SourceDateList.size() == 0) {
            frame.setVisibility(View.VISIBLE);
            no_contaxt.setVisibility(View.GONE);
            no_network.setVisibility(View.VISIBLE);
            contaxt_bg.setVisibility(View.GONE);
        }
    }

    private void initData() {
        sideBar.setTextView(dialog);
        new AsyncTaskConstact(mLoadingView).execute(0);
    }

    private class AsyncTaskConstact extends AsyncTaskBase {

        public AsyncTaskConstact(LoadingView loadingView) {
            super(loadingView);
        }

        @Override
        protected Integer doInBackground(Integer... params) {
            int result = -1;
            UserService service = new UserService();
            String jsonString = service.getUsers("");
            if (Tools.isNull(jsonString)) {
                return 0;
            } else if (jsonString.equals("outTime")) {
                return 2;// 超时
            } else if (jsonString.equals("NetworkError")) {
                return 3;// 网络异常
            }

            // callRecords = ConstactUtil.getAllCallRecords(mContext);
            callRecords = UserParser.getAllCallRecords(mContext, jsonString);
            if (callRecords == null) {
                return 0;
            }
            result = 1;
            return result;
        }

        @Override
        protected void onPostExecute(final Integer result) {
            super.onPostExecute(result);
            String s = "查询异常";
            if ("en".equals(mEns)) {
                s = "Query exception";
            }else{
                s = "查询异常";
            }
            if (result == 0) {
                mLoadingView.setVisibility(View.GONE);
                Tools.showInfo(mContext, s);
                noNetWork();
                sortListView.setCanRefresh(true);
                sortListView.onRefreshComplete(); // 下拉刷新完成
                return;
            } else if (result == 2) {
                mLoadingView.setVisibility(View.GONE);
                Tools.showInfo(mContext, s);
                sortListView.setCanRefresh(true);
                noNetWork();
                sortListView.onRefreshComplete(); // 下拉刷新完成
                return;
            } else if (result == 3) {
                mLoadingView.setVisibility(View.GONE);
                Tools.showInfo(mContext, s);
                noNetWork();
                sortListView.setCanRefresh(true);
                sortListView.onRefreshComplete(); // 下拉刷新完成
                return;
            }

            new Thread() {
                public void run() {
                    if (result == 1) {
                        List<String> constact = new ArrayList<String>();
                        for (Iterator<String> keys = callRecords.keySet()
                                .iterator(); keys.hasNext();) {
                            String key = keys.next();
                            constact.add(key);
                        }
                        String[] names = new String[] {};
                        names = constact.toArray(names);
                        SourceDateList = filledData(names);
                        DbUtils db = DbUtils.create(mContext, UserManager
                                .getManager().getUser().userId + "chat");
                        try {
                            if (db.tableIsExist(CoworkerEntity.class)) {
                                db.deleteAll(CoworkerEntity.class);
                            }
                            db.saveAll(SourceDateList);
                        } catch (DbException e) {
                            Tools.handle(e);
                        }
                        // 根据a-z进行排序源数据
                        Collections.sort(SourceDateList, pinyinComparator);
                        handler.sendEmptyMessage(2);
                    }
                }
            }.start();

        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    adapter.updateListView(SourceDateList);
                    sortListView.setAdapter(adapter);
                    contaxt_bg.setVisibility(View.VISIBLE);
                    frame.setVisibility(View.GONE);
                    mLoadingView.setVisibility(View.GONE);
                    sortListView.setCanRefresh(true);
                    adapter.notifyDataSetChanged();
                    sortListView.onRefreshComplete(); // 下拉刷新完成
                    noData();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @SuppressLint("DefaultLocale")
    private List<CoworkerEntity> filledData(String[] date) {
        List<CoworkerEntity> mSortList = new ArrayList<CoworkerEntity>();

        for (int i = 0; i < date.length; i++) {
            CoworkerEntity sortModel = new CoworkerEntity();
            sortModel.setName(date[i]);
            // 汉字转换成拼音
            // String pinyin = characterParser.getSelling(date[i]);
            if (date[i].trim().equals("") || date[i].trim().equals("null")) {
                continue;
            }
            String pinyin = PinyinUtils.getPingYin(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // String sortString=PinyinUtils.cn2FirstSpell(date[i]);
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            User user = callRecords.get(date[i]);
            sortModel.setDepartment(user.getName());
            sortModel.setEmail(user.getEmail());
            sortModel.setPhone(user.getPhone());
            sortModel.setFax(user.getFax());
            sortModel.setMobile(user.getMobile());
            sortModel.setTitle(user.getTitle());
            sortModel.setCompany(user.getCompany());
            sortModel.setCountry(user.getCountry());
            sortModel.setPostalcode(user.getPostalcode());
            sortModel.setCity(user.getCity());
            sortModel.setShengri(user.getShengri());
            sortModel.setXingbie(user.getXingbie());
            sortModel.setEmployeenum(user.getEmployeenum());
            sortModel.setId(user.getId());
            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<CoworkerEntity> filterDateList = new ArrayList<CoworkerEntity>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (CoworkerEntity sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(name).startsWith(
                        filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        if(filterDateList.size()<=0){
            sortListView.setVisibility(View.GONE);
        }else{
            sortListView.setVisibility(View.VISIBLE);
            adapter.updateListView(filterDateList);
        }

    }

}
